/*
 * 0180. 二进制表示
 * 给定一个数将其转换为二进制（均用字符串表示），如果这个数的小数部分不能在 32 个字符之内来精确地表示，则返回 "ERROR"。
 * https://www.lintcode.com/problem/binary-representation/description
 * 
 * 样例
 * n = "3.72", 返回 "ERROR".
 * n = "3.5", 返回 "11.1".
 * 
 * 2018.07.02 @jeyming
 */
package binary_representation_0180;

public class Binary_representation_0180 {
	/**
     * @param n: Given a decimal number that is passed in as a string
     * @return: A string
     */
    public String binaryRepresentation(String n) {
        // write your code here
    	StringBuffer result = new StringBuffer();
    	String[] str = n.split("\\.");
    	if(str.length == 0) {
    		return "ERROR";
    	} else if (str.length == 1) {
    		int a = Integer.parseInt(str[0]);
    		while(a > 0) {
    			result.append(a % 2);
    			a /= 2;
    		}
    		return result.reverse().toString();
    	} else {
    		if(str[0].equals("0") && str[1].equals("0")) {
    			return "0";
    		} else if(str[0].equals("0")) {
    			result.append("0.");
    			double d = Double.parseDouble(n);
    			while(d != 0.0) {
    				if(result.length() > 32) {
    					return "ERROR";
    				} else {
    					double d_ = d * 2;
    					int a = (int) d_;
    					result.append(a);
    					d = d_ - a;
    				}
    			}
    			return result.toString();
    		} else {
    			int a = Integer.parseInt(str[0]);
    			while(a > 0) {
    				result.append(a % 2);
    				a /= 2;
    			}
    			result.reverse();
    			if(!str[1].equals("0")) {
    				result.append(".");
    				double d = Double.parseDouble("0." + str[1]);
    				int cnt = 0;
    				while(d != 0.0) {
    					++cnt;
    					if(cnt > 32) {
    						return "ERROR";
    					} else {
    						double d_ = d * 2;
    						int x = (int)d_;
    						result.append(x);
    						d = d_ - x;
    					}
    				}
    			}
    			return result.toString();
    		}
    	}
    }

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
